package xrate

import (
	"fmt"

	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 查询用户的抽奖记录
//
//	uid		用户ID
//	bid		批次ID
//	offset	跳过条数
//	limit	查询条数
func UserList(uid, bid uint, offset, limit int) (int64, []UserProject, error) {
	if _default.DB == nil {
		return 0, nil, xerror.New("数据库未连接")
	}
	// 获取用户的抽奖记录
	db := _default.DB.Table(_default.UserName).
		Joins(fmt.Sprintf("LEFT JOIN %s ON %s.`batch_id` = %s.`id`", _default.BatchName, _default.UserName, _default.BatchName)).
		Joins(fmt.Sprintf("LEFT JOIN %s ON %s.`project_id` = %s.`id`", _default.ProjectName, _default.UserName, _default.ProjectName)).
		Joins(fmt.Sprintf("LEFT JOIN %s ON %s.`start_id` = %s.`id`", _default.StartName, _default.UserName, _default.StartName)).
		Where(fmt.Sprintf("%s.`user_id`", _default.UserName), uid)
	if bid > 0 {
		db = db.Where(fmt.Sprintf("%s.`batch_id`", _default.UserName), bid)
	}
	var count int64
	err := db.Count(&count).Error
	if err != nil {
		return 0, nil, xerror.New("抽奖条数查询失败")
	}
	if count == 0 {
		// 还没有开始抽奖
		return 0, []UserProject{}, nil
	}
	lis := []UserProject{}
	err = db.
		Select(fmt.Sprintf("%s.`id`,%s.`project_id`,%s.`start_id`,%s.`batch_id`,%s.`is_used`,%s.`msg`,%s.`created_at`,%s.`name` AS `batch_name`,%s.`name` AS `start_name`,%s.`name` AS `project_name`",
			_default.UserName, _default.UserName, _default.UserName, _default.UserName, _default.UserName, _default.UserName, _default.UserName,
			_default.BatchName, _default.StartName, _default.ProjectName,
		)).
		Order(fmt.Sprintf("%s.`id` DESC", _default.UserName)).
		Offset(offset).
		Limit(limit).
		Find(&lis).
		Error
	if err != nil {
		return 0, nil, xerror.New("抽奖列表查询失败")
	}
	return count, lis, nil
}
